<template>
  <div class="profile-container">
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button @click="goBack" class="back-button">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回上一级</span>
      </el-button>
    </div>
    
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>个人资料</h3>
        </div>
      </template>
      
      <!-- 头像上传 -->
      <div class="avatar-section">
        <el-avatar :size="120" :src="userInfo.avatar || defaultAvatar" class="avatar-display" />
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadAvatar"
          accept="image/*"
        >
          <el-button type="primary" size="small">
            <el-icon><Upload /></el-icon> 更换头像
          </el-button>
        </el-upload>
        <div class="avatar-tips">支持JPG、PNG、GIF、WEBP格式，文件大小不超过5MB</div>
      </div>
      
      <!-- 基本信息表单 -->
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="profile-form">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="部门" prop="department">
          <el-input v-model="form.department" placeholder="请输入部门" />
        </el-form-item>
        
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitProfile" :loading="saving">保存资料</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 修改密码 -->
    <el-card class="profile-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <h3>修改密码</h3>
        </div>
      </template>
      
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" class="profile-form">
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="passwordForm.old_password" type="password" placeholder="请输入旧密码" show-password />
        </el-form-item>
        
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="passwordForm.new_password" type="password" placeholder="请输入新密码（至少6位）" show-password />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="passwordForm.confirm_password" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitPassword" :loading="changingPassword">修改密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api'

const router = useRouter()
const formRef = ref(null)
const passwordFormRef = ref(null)
const saving = ref(false)
const changingPassword = ref(false)

const defaultAvatar = ''

const userInfo = ref({
  username: '',
  email: '',
  avatar: '',
  phone: '',
  department: '',
  position: ''
})

const form = reactive({
  email: '',
  phone: '',
  department: '',
  position: ''
})

const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.new_password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  old_password: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const loadUserInfo = async () => {
  try {
    const data = await authAPI.currentUser()
    userInfo.value = data
    form.email = data.email || ''
    form.phone = data.phone || ''
    form.department = data.department || ''
    form.position = data.position || ''
    
    // 更新localStorage中的用户信息
    localStorage.setItem('user_info', JSON.stringify(data))
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const uploadAvatar = async ({ file }) => {
  try {
    const response = await authAPI.uploadAvatar(file)
    userInfo.value.avatar = response.avatar
    
    // 更新localStorage中的头像
    const storedUser = JSON.parse(localStorage.getItem('user_info') || '{}')
    storedUser.avatar = response.avatar
    localStorage.setItem('user_info', JSON.stringify(storedUser))
    
    ElMessage.success('头像上传成功')
  } catch (error) {
    const errorMsg = error.response?.data?.error || '头像上传失败'
    ElMessage.error(errorMsg)
  }
}

const submitProfile = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      const response = await authAPI.updateProfile(form)
      ElMessage.success('资料更新成功')
      
      // 更新userInfo
      await loadUserInfo()
    } catch (error) {
      const errorMsg = error.response?.data?.error || '更新失败'
      ElMessage.error(errorMsg)
    } finally {
      saving.value = false
    }
  })
}

const resetForm = () => {
  form.email = userInfo.value.email || ''
  form.phone = userInfo.value.phone || ''
  form.department = userInfo.value.department || ''
  form.position = userInfo.value.position || ''
}

const submitPassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    changingPassword.value = true
    try {
      await authAPI.changePassword({
        old_password: passwordForm.old_password,
        new_password: passwordForm.new_password
      })
      
      ElMessage.success('密码修改成功，请重新登录')
      
      // 清除登录信息
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
      
      // 跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } catch (error) {
      const errorMsg = error.response?.data?.error || '密码修改失败'
      ElMessage.error(errorMsg)
    } finally {
      changingPassword.value = false
    }
  })
}

const resetPasswordForm = () => {
  passwordForm.old_password = ''
  passwordForm.new_password = ''
  passwordForm.confirm_password = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
}

.back-button-container {
  margin-bottom: 20px;
}

.back-button {
  background: rgba(58, 132, 255, 0.1);
  border-color: #3a84ff;
  color: #3a84ff;
}

.back-button:hover {
  background: rgba(58, 132, 255, 0.2);
  border-color: #5a9cff;
  color: #5a9cff;
}

.profile-card {
  background: #1e2835;
  border: 1px solid rgba(58, 132, 255, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #3a84ff;
  font-size: 20px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
  border-bottom: 1px solid rgba(58, 132, 255, 0.2);
  margin-bottom: 30px;
}

.avatar-display {
  margin-bottom: 20px;
  border: 3px solid #3a84ff;
}

.avatar-uploader {
  margin-bottom: 10px;
}

.avatar-tips {
  color: #909399;
  font-size: 12px;
  text-align: center;
}

.profile-form {
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.05);
  box-shadow: none;
  border: 1px solid rgba(58, 132, 255, 0.3);
}

:deep(.el-input__wrapper:hover) {
  border-color: #3a84ff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #3a84ff;
  box-shadow: 0 0 0 2px rgba(58, 132, 255, 0.1);
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.02);
  border-color: rgba(58, 132, 255, 0.1);
}
</style>
